package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import com.sun.xml.internal.ws.policy.privateutil.RuntimePolicyUtilsException;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {
    //http://ip:port/provider/sentinel01
    @GetMapping("/sentinel01")
    public String doSentinel01(){
        return "sentinel test 01";
    }
    //http://ip:port/provider/sentinel02
    @GetMapping("/sentinel02")
    public String doSentinel02(){
        return "sentinel test 02";
    }

    @Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
    public String doSentinel03(){
        return resourceService.doGetResource();
        //return "sentinel test 03";
    }
    @GetMapping("/sentinel04")
    public String doSentinel04(){
        resourceService.doGetResource();
        return "sentinel test 04";
    }

    /**
     * 演示降级(熔断)操作，通过如下代码创造降级的条件：
     * 1)服务响应速度慢一些
     * 2)服务不稳定，经常出现异常
     */
    private AtomicLong atomicLong=new AtomicLong(1);

    //http://localhost:8081/provider/sentinel05
    @GetMapping("/sentinel05")
    public String doSentinel05() throws InterruptedException {
        long count = atomicLong.getAndIncrement();
        String threadName = Thread.currentThread().getName();
        System.out.println("threadName="+threadName);
        if(count%2==0){
            Thread.sleep(200);//模拟耗时(让线程休眠)
            //模拟系统异常(系统运行过程可能会因为一些因素出现各种异常)
            //throw new RuntimeException("服务调用失败");
        }
        return "sentinel test 05";
    }

    //http://localhost:8081/provider/sentinel01?id=10
    @GetMapping("/sentinel06")
    public String doSentinel06(@RequestParam("id") Integer id){
        return resourceService.doGetResource(id);
        //return "Get Resource By "+id;
    }


}
